package com.dctp.ems.controller;

import com.dctp.common.cache.UserCache;
import com.dctp.common.controller.BaseController;
import com.dctp.common.utils.DateUtil;
import com.dctp.common.vo.JsonResult;
import com.dctp.common.vo.PageResult;
import com.jfinal.aop.Before;
import com.jfinal.core.Path;
import com.jfinal.plugin.activerecord.Db;
import com.jfinal.plugin.activerecord.Record;
import com.jfinal.plugin.activerecord.tx.Tx;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;

@Path("/accountLimit")
public class AccountLimitController extends BaseController {

    /**
     * GET /accountLimit/list
     * 分页查询账户限仓
     */
    public void list() {
        int page = getInt("currentPage", 1);
        int pageSize = getInt("pageSize", 10);
        Long userId = getParaToLong("user_id");
        StringBuilder where = new StringBuilder(" WHERE 1=1 ");
        List<Object> params = new ArrayList<>();
        if (userId != null) {
            where.append(" AND user_id = ?");
            params.add(userId);
        }
        String select = "SELECT * ";
        String from = "FROM dctp_account_limit" + where + " ORDER BY id DESC";
        var p = Db.paginate(page, pageSize, select, from, params.toArray());
        List<Record> list = p.getList();
        for (Record r : list) {
            Long uid = r.getLong("user_id");
            if (uid != null) {
                r.set("user", UserCache.getBasic(uid));
            }
        }
        renderJson(JsonResult.successWithData(
            new PageResult<>(list, p.getTotalRow(), pageSize, page)
        ));
    }

    /**
     * POST /accountLimit/add
     * 添加账户限仓
     */
    @Before(Tx.class)
    public void add() {
        Record body = jsonBody();
        if (body.get("user_id") == null) {
            renderJson(JsonResult.failWithMessage("user_id不能为空"));
            return;
        }
        if (!checkLimitParams(body)) {
            renderJson(JsonResult.failWithMessage("限仓参数必须为非负整数或空"));
            return;
        }
        // 检查唯一
        Long exist = Db.queryLong("SELECT id FROM dctp_account_limit WHERE user_id=?", body.getLong("user_id"));
        if (exist != null) {
            renderJson(JsonResult.failWithMessage("该用户限仓已存在"));
            return;
        }
        body.set("create_time", DateUtil.now());
        if (!Db.save("dctp_account_limit", body)) {
            throw new RuntimeException("新增账户限仓失败");
        }
        renderJson(JsonResult.success());
    }

    /**
     * POST /accountLimit/update/:id
     * 更新账户限仓
     */
    @Before(Tx.class)
    public void update() {
        Long id = getParaToLong(0);
        if (id == null) {
            renderJson(JsonResult.failWithMessage("参数缺失"));
            return;
        }
        Record body = jsonBody();
        if (body.getColumns().isEmpty()) {
            renderJson(JsonResult.failWithMessage("无有效字段"));
            return;
        }
        if (!checkLimitParams(body)) {
            renderJson(JsonResult.failWithMessage("限仓参数必须为非负整数或空"));
            return;
        }
        body.set("id", id)
            .set("update_time", DateUtil.now());
        boolean updated = Db.update("dctp_account_limit", body);
        if (!updated) {
            renderJson(JsonResult.failWithMessage("更新失败或记录不存在"));
            return;
        }
        renderJson(JsonResult.success());
    }

    /**
     * POST /accountLimit/delete/:id
     * 删除账户限仓
     */
    @Before(Tx.class)
    public void delete() {
        Long id = getParaToLong(0);
        if (id == null) {
            renderJson(JsonResult.failWithMessage("参数缺失"));
            return;
        }
        int r = Db.update("DELETE FROM dctp_account_limit WHERE id=?", id);
        if (r == 0) {
            renderJson(JsonResult.failWithMessage("删除失败或记录不存在"));
        } else {
            renderJson(JsonResult.success());
        }
    }

    /**
     * GET /accountLimit/all
     * 获取所有启用的账户限仓
     */
    public void all() {
        List<Record> list = Db.find("SELECT * FROM dctp_account_limit WHERE limit_enabled=1 ORDER BY id DESC");
        renderJson(JsonResult.successWithData(list));
    }

    private boolean isValidLimitNumber(Object v) {
        if (v == null) return true;
        try {
            BigDecimal val = new BigDecimal(v.toString());
            return val.scale() <= 0 && val.compareTo(BigDecimal.ZERO) >= 0;
        } catch (Exception e) {
            return false;
        }
    }
    private boolean checkLimitParams(Record body) {
        String[] keys = {"daily_order_limit", "single_order_lot_limit", "max_position_lot", "daily_max_open_lot"};
        for (String key : keys) {
            if (!isValidLimitNumber(body.get(key))) return false;
        }
        return true;
    }
}
